package com.qiyu.tech.tcc.starter.service;

import com.qiyu.tech.tcc.starter.constants.CommonConstants;
import com.qiyu.tech.tcc.starter.model.Order;
import com.qiyu.tech.tcc.starter.model.StockFreeze;
import com.qiyu.tech.tcc.starter.model.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author linhao
 * @date created in 8:18 下午 2020/11/3
 */
@Service
public class TransactionService {

    @Resource
    private GoodsService goodsService;

    @Resource
    private UserService userService;

    @Resource
    private OrderService orderService;

    @Resource
    private StockFreezeService stockFreezeService;


    public boolean doTccVersion2(int userId, int goodsId, int stock) {
        User user = userService.queryByUserId(userId);
        StockFreeze stockFreeze = new StockFreeze();
        stockFreeze.setGoodId(goodsId);
        stockFreeze.setUserId(user.getUserId());
        stockFreeze.setStock(stock);
        stockFreeze.setValid(CommonConstants.StockFreezeEnum.LOCKING.getCode());
        int id = stockFreezeService.insertOne(stockFreeze);

        //锁定库存
        if (id > 0) {
            //插入订单
            Order order = new Order();
            order.setOrderNo(String.valueOf(UUID.randomUUID()));
            orderService.insertOrder(order);
            //扣减库存 解除锁定状态
            stockFreezeService.changeValidStatus(id, CommonConstants.StockFreezeEnum.UN_LOCK.getCode());
            //扣减库存
            goodsService.updateStock(stock, goodsId);
            //增加优惠券
            userService.addCoupon(userId);
            System.out.println("正常处理");
            return true;
        }

        return false;
    }
}
